package com.mmall.controller.backend;

import com.google.common.collect.Maps;
import com.mmall.common.Const;
import com.mmall.common.ResponseCode;
import com.mmall.common.ServerResponse;
import com.mmall.pojo.Product;
import com.mmall.pojo.User;
import com.mmall.service.IFileService;
import com.mmall.service.IProductService;
import com.mmall.service.IUserService;
import com.mmall.util.PropertiesUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;

@Controller
@RequestMapping("/manage/product")
public class ProductManageController {

    @Autowired
    private IUserService iUserService;

    @Autowired
    private IProductService iProductService;

    @Autowired
    private IFileService iFileService;

    @RequestMapping(value = "save.do")
    @ResponseBody
    public ServerResponse productSave(HttpSession session, Product product){
        ServerResponse responseForCheckAdminRole = checkAdminRole(session);
        if(responseForCheckAdminRole.isSuccess()){
            return iProductService.saveOrUpdateProduct(product);
        }else{
            return responseForCheckAdminRole;
        }
    }

    @RequestMapping(value = "set_sale_status.do")
    @ResponseBody
    public ServerResponse setSaleStatus(HttpSession session, Integer productId, Integer productStatus){
        ServerResponse responseForCheckAdminRole = checkAdminRole(session);
        if(responseForCheckAdminRole.isSuccess()){
            return iProductService.setSaleStatus(productId, productStatus);
        }else{
            return responseForCheckAdminRole;
        }
    }


    @RequestMapping(value = "detail.do")
    @ResponseBody
    public ServerResponse getDetail(HttpSession session, Integer productId){
        ServerResponse responseForCheckAdminRole = checkAdminRole(session);
        if(responseForCheckAdminRole.isSuccess()){
            return iProductService.manageProductDetail(productId);
        }else{
            return responseForCheckAdminRole;
        }
    }


    @RequestMapping(value = "list.do")
    @ResponseBody
    public ServerResponse getList(HttpSession session,
                                  @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                                  @RequestParam(value = "pageSize", defaultValue = "10")int pageSize){
        ServerResponse responseForCheckAdminRole = checkAdminRole(session);
        if(responseForCheckAdminRole.isSuccess()){
            return iProductService.getProductList(pageNum, pageSize);
        }else{
            return responseForCheckAdminRole;
        }
    }

    @RequestMapping(value = "search.do")
    @ResponseBody
    public ServerResponse productSearch(HttpSession session,
                                  String productName, Integer productId,
                                  @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                                  @RequestParam(value = "pageSize", defaultValue = "10")int pageSize){
        ServerResponse responseForCheckAdminRole = checkAdminRole(session);
        if(responseForCheckAdminRole.isSuccess()){
            return iProductService.searchProduct(productName,productId,pageNum,pageSize);
        }else{
            return responseForCheckAdminRole;
        }
    }

    @RequestMapping(value = "upload.do")
    @ResponseBody
    public ServerResponse upload(@RequestParam(value = "upload_file", required = false) MultipartFile file,
                                 HttpServletRequest request,
                                 HttpSession session){
        ServerResponse responseForCheckAdminRole = checkAdminRole(session);
        if(responseForCheckAdminRole.isSuccess()){
            String path = request.getSession().getServletContext().getRealPath("upload");
            String targetFileName = iFileService.upload(file,path);
            String url = PropertiesUtil.getProperty("ftp.server.http.prefix") + targetFileName;
            Map fileMap = Maps.newHashMap();
            fileMap.put("uri", targetFileName);
            fileMap.put("url", url);

            return ServerResponse.createBySuccess(fileMap);
        }else{
            return responseForCheckAdminRole;
        }
    }

    @RequestMapping(value = "richtext_img_upload.do")
    @ResponseBody
    public Map richtextImgUpload(@RequestParam(value = "upload_file", required = false) MultipartFile file,
                                 HttpServletRequest request,
                                 HttpSession session,
                                 HttpServletResponse response){
        Map resultMap = Maps.newHashMap();
        User user = (User)session.getAttribute(Const.CURRENT_USER);
        if(user == null){
            resultMap.put("success", false);
            resultMap.put("msg", "请登录");
            return resultMap;
        }

        if(iUserService.checkAdminRole(user).isSuccess()){

            // 富文本中返回值有自己的要求: 按照simditor的要求进行返回
            // <http://simditor.tower.im/docs/doc-config.html#anchor-upload>
//            {
//                "success": true/false,
//                "msg": "error message", # optional
//                "file_path": "[real file path]"
//            }
            String path = request.getSession().getServletContext().getRealPath("upload");
            String targetFileName = iFileService.upload(file,path);
            if(StringUtils.isBlank(targetFileName)){
                resultMap.put("success", false);
                resultMap.put("msg", "上传失败");
                return resultMap;
            }
            String url = PropertiesUtil.getProperty("ftp.server.http.prefix") + targetFileName;

            resultMap.put("success", true);
            resultMap.put("msg", "上传成功");
            resultMap.put("file_path", url);

            response.addHeader("Access-Control-Allow-Headers", "X-File-Name");

            return resultMap;
        }else{
            resultMap.put("success", false);
            resultMap.put("msg", "不是管理员,无权操作");
            return resultMap;
        }
    }

    private ServerResponse checkAdminRole(HttpSession session){
        User user = (User)session.getAttribute(Const.CURRENT_USER);
        if(user == null){
            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(), "用户未登录");
        }
        return iUserService.checkAdminRole(user);
    }
}
